import { AssistException } from './assist-exception'

/**
 * 条件类型
 */
export type AssistCondition = boolean | (() => boolean)

/**
 * 辅助类
 */
export class Assist {
  /**
   * 解析条件
   * @param condition 条件
   * @returns {boolean} 返回布尔值
   */
  static resolveCondition(condition: AssistCondition): boolean {
    return typeof condition === 'function' ? !!condition() : !!condition
  }

  /**
   * 抛出异常
   * @param message 错误信息
   */
  static threw(message: string): void
  /**
   * 抛出异常
   * @param exception AssistException 异常对象
   */
  static threw(exception: AssistException): void
  /**
   * 抛出异常
   * @param error Error 对象
   */
  static threw(error: Error): void
  /**
   * 抛出异常
   * @param condition 条件
   * @param message 错误信息
   */
  static threw(condition: AssistCondition, message: string): void
  /**
   * 抛出异常
   * @param condition 条件
   * @param message AssistException 异常对象
   */
  static threw(condition: AssistCondition, exception: AssistException): void

  /**
   * 抛出异常
   * @param arg0 AssistCondition 条件
   * @param arg1 错误信息
   */
  static threw(arg0: string | AssistException | Error | AssistCondition, arg1?: string | AssistException): void {
    if (typeof arg0 === 'string') {
      throw new AssistException(arg0)
    }

    if (arg0 instanceof AssistException) {
      throw arg0
    }

    if (arg0 instanceof Error) {
      throw new AssistException(arg0.message)
    }

    if (Assist.resolveCondition(arg0)) {
      if (typeof arg1 === 'string') {
        throw new AssistException(arg1)
      } else {
        throw arg1
      }
    }
  }

  /**
   * 数据为空抛出异常，返回不为空的原数据
   * @param obj
   * @param message
   * @returns
   */
  static notNull<T = unknown>(obj: T, message: string): NonNullable<T> {
    if (obj == null) {
      throw new AssistException(message)
    }

    return obj
  }
}
